C# / ASP.NET - Web 應用程序鎖定 (C# / ASP.NET - Web Application locking)


問題描述

C# / ASP.NET ‑ Web 應用程序鎖定 (C# / ASP.NET ‑ Web Application locking)

我正在開發一個 C#/ASP.NET Web 應用程序,並且在很多情況下我需要進行鎖定。理想情況下,我希望鎖獨立運行,因為它們彼此無關。我一直在考慮 [MethodImpl(MethodImplOptions.Synchronized)] 和一些使用 lock() 的方法,但我有一些問題/疑慮。

看起來 MethodImplOptions.Synchronized 基本上會做lock(this)`。如果是這種情況,似乎一個線程進入任何同步方法都會阻止所有其他線程進入任何同步方法。那正確嗎?如果是這樣,這還不夠細化。在這一點上,我似乎還不如使用 Application.Lock。(但如果我錯了,請糾正我。)

關於 lock(),我想弄清楚我應該傳入什麼。我應該創建一組僅用於此目的的對象,並將每個對像用於不同的鎖?有沒有更好的方法?

提前致謝!


參考解法

方法 1:

My preference is to create an object specifically for the lock.

private object lockForSomeResource = new object();

in the class that is managing the contentious resource. Jeff Richter posted an article I read some time ago that recommended this.

You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.

方法 2:

I have posted a similar question on this forum, that may help you. Following is the link

Issue writing to single file in Web service in .NET

方法 3:

You can expose some static reference or a singleton, and lock() that.

Maybe you can care to explain why you need such locking and what you will use it for?

方法 4:

Creating discrete object instances at static/application level is the best way for plain exclusive locking.

Should also consider if reader/writer lock instances at application level could also help improve your application concurrency e.g. for reading and updating lists, hashes etc.

(by Matthew ColeHamish Smithpradeeptpcruizerstephbu)

參考文件

  1. C# / ASP.NET ‑ Web Application locking (CC BY‑SA 2.5/3.0/4.0)

#ASP.NET #locking #synchronization #C#






相關問題

System.Reflection.Assembly.LoadFile 鎖定文件 (System.Reflection.Assembly.LoadFile Locks File)

如何在沒有全局變量的情況下一直保留我的變量? (How can I keep my variable all the time without global variables?)

C# / ASP.NET - Web 應用程序鎖定 (C# / ASP.NET - Web Application locking)

關閉模態對話框窗口後 ASP.NET 刷新父頁面 (ASP.NET Refresh Parent Page after Closing Modal Dialog Window)

無法將 NULL 值傳遞給數據庫 (Unable to pass NULL value to database)

wcf:將用戶名添加到消息頭是否安全? (wcf: adding username to the message header is this secure?)

使用 ASP.Net 教初學者 Web 開發的小項目想法 (Small projects ideas to teach beginners web development using ASP.Net)

SQL Server - 分組、擁有和計數 (SQL Server - Group by, having and count in a mix)

企業庫異常處理應用程序塊和日誌記錄應用程序塊在 ASP.NET 中的正確使用 (Enterprise Library Exception Handling Application Block and Logging Application Block proper use in ASP.NET)

來自proc的asp.net多個結果集:是否有必要將結果映射到類?如果是這樣,怎麼做? (asp.net multiple result set from proc: is it necessary to map results to class? If so, how?)

如何在測試工具中實例化 asp.net 代碼隱藏類? (How can I instantiate an asp.net codebehind class in a test harness?)

Web 窗體用戶控制事件,需要在頁面加載後添加 (Web Form User Control Event, needs to be added after page loads)







留言討論